package com.example.book.crawler.task;

import com.example.book.common.executor.interfaces.ExecutorAsyncService;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.crawler.entity.CrawlerContent;
import com.example.book.crawler.service.CrawlerContentService;
import com.example.book.in.entity.BookCatalog;
import com.example.book.in.entity.BookContent;
import com.example.book.in.service.BookCatalogService;
import com.example.book.in.service.BookContentService;
import com.example.book.in.service.BookInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

//@Component
public class ContentTask {

    @Autowired
    private CrawlerContentService crawlerContentService;
    @Autowired
    private BookCatalogService bookCatalogService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ExecutorAsyncService executorAsyncService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void collectionContent() {
        Boolean content_next = (Boolean) redisService.get("content_next");
        if (null == content_next || content_next) {
            redisService.set("content_next", false);
            List<CrawlerContent> crawlerContents = crawlerContentService.findListByLimit(100);
            handler(crawlerContents);
            redisService.set("content_next", true);
        }
    }

    private void handler(List<CrawlerContent> crawlerContents) {
        BookCatalog bookCatalog = null;
        for (CrawlerContent cc : crawlerContents) {
            bookCatalog = new BookCatalog();
            bookCatalog.setCatalogIndex(cc.getCatalogIndex());
            bookCatalog.setBookInfoId(cc.getBookInfoId());
            bookCatalog.setCatalogName(cc.getCatalogName());
            Map<String, Object> map = null;
            try {
                map = (Map<String, Object>) redisTemplate.opsForList().rightPop(Constants.IP_QUEUE, 2, TimeUnit.SECONDS);
                // 不可以异步
                executorAsyncService.saveCatalogByStatus(cc, bookCatalog, map);
            } catch (Exception e) {
                e.printStackTrace();
                if (map != null) {
                    redisTemplate.opsForList().leftPush(Constants.IP_QUEUE, map);
                }
            }
        }
    }
}
